﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JGSY.SerialCommunication.UpperComputer.Core.AOP.ThirdPartyLibrary
{
    /// <summary>
    ///   定义自定义特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class LogCastleDynamicProxyAttribute : Attribute, IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            // 前置处理
            Console.WriteLine($"LogAspectCastleDynamicProxyAttribute方法执行前: {invocation.Method.Name}");
            Console.WriteLine($"参数: {string.Join(", ", invocation.Arguments)}");
            var stopwatch = Stopwatch.StartNew();
            try
            {

                // 调用实际方法
                invocation.Proceed();
                Console.WriteLine($"方法执行后: 返回值 {invocation.ReturnValue}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"方法异常: {ex.Message}");
                throw;
            }
            finally
            {
                stopwatch.Stop();

                // 后置处理
                //Console.WriteLine($"方法执行后: 返回值 {invocation.ReturnValue}");
                Console.WriteLine($"方法 {invocation.Method.Name} 执行完成");
                Console.WriteLine($"返回值: {invocation.ReturnValue ?? "null"}");
                Console.WriteLine($"执行时间: {stopwatch.ElapsedMilliseconds} ms");
                Console.WriteLine("----------------------------------------");
            }
        }
    }
}
